/*
 * SyncResource.java
 *
 * Created on April 12, 2007, 1:39 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.atomojo.auth.service.app;

import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.UUID;
import java.util.logging.Level;
import org.atomojo.app.client.XMLRepresentationParser;
import org.atomojo.auth.service.db.AuthDB;
import org.atomojo.auth.service.db.Group;
import org.atomojo.auth.service.db.Realm;
import org.atomojo.auth.service.db.RealmUser;
import org.atomojo.auth.service.db.User;
import org.atomojo.auth.service.db.XML;
import org.infoset.xml.Document;
import org.infoset.xml.Element;
import org.infoset.xml.util.DocumentDestination;
import org.restlet.Request;
import org.restlet.data.CharacterSet;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.ServerResource;

/**
 *
 * @author alex
 */
public class RealmUserResource extends ServerResource
{
   
   static String GROUP_FACET = "groups";
   AuthDB db;
   XMLRepresentationParser parser = XML.createParser();
   XMLRepresentationParser postParser = XML.createParser();
   String userId;
   String userAlias;
   String facet;
   String facetName;
   String facetId;
   /** Creates a new instance of SyncResource */
   public RealmUserResource() {
      setNegotiated(false);
   }

   protected void doInit() {
      db = (AuthDB)getRequest().getAttributes().get(AuthApplication.DB_ATTR);
      parser.addAllowedElement(XML.USER_NAME);
      postParser.addAllowedElement(XML.GROUP_NAME);
      postParser.addAllowedElement(XML.PASSWORD_NAME);
      userId = AuthApplication.getStringAttribute(getRequest(),"user-id",null);
      userAlias = AuthApplication.getStringAttribute(getRequest(),"user-alias",null);
      facet = AuthApplication.getStringAttribute(getRequest(),"facet",null);
      facetId = AuthApplication.getStringAttribute(getRequest(),"facet-id",null);
      facetName = AuthApplication.getStringAttribute(getRequest(),"facet-name",null);
   }
   
   public Representation get()
   {
      try {
         RealmUser user = fetch();
         if (user!=null) {
            if (facet!=null) {
               if (facet.equals(GROUP_FACET)) {
                  if (facetName==null && facetId==null) {
                     Representation entity = new DBIteratorRepresentation(MediaType.APPLICATION_XML,XML.GROUPS_NAME,user.getGroups(),false);
                     entity.setCharacterSet(CharacterSet.UTF_8);
                     return entity;
                  } else {
                     Group group = fetchGroup(user);
                     if (group!=null && user.isMemberOf(group)) {
                        Representation entity = new DBObjectRepresentation(MediaType.APPLICATION_XML,group);
                        entity.setCharacterSet(CharacterSet.UTF_8);
                        return entity;
                     } else {
                        getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                        return null;
                     }
                  }
               } else {
                  getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                  return null;
               }
            } else {
               Representation entity = new DBObjectRepresentation(MediaType.APPLICATION_XML,user);
               entity.setCharacterSet(CharacterSet.UTF_8);
               return entity;
            }
         }
         getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
         return null;
      } catch (SQLException ex) {
         getContext().getLogger().log(Level.SEVERE,"Cannot get realm user from database.",ex);
         getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
         return new StringRepresentation("Exception during processing, see logs.");
      }
   }
   
   public Representation put(Representation entity)
   {
      if (!XMLRepresentationParser.isXML(entity.getMediaType())) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("Non-XML media type for entity body: "+entity.getMediaType().getName());
      }
      Document doc = null;
      
      try {
         DocumentDestination dest = new DocumentDestination();
         parser.parse(entity,dest);
         doc = dest.getDocument();
      } catch (Exception ex) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("XML parse error: "+ex.getMessage());
      }
      try {
         RealmUser user = fetch();
         if (user!=null) {
            Element top = doc.getDocumentElement();
            String alias = top.getAttributeValue("alias");
            Element name = top.getFirstElementNamed(XML.NAME_NAME);
            Element email = top.getFirstElementNamed(XML.EMAIL_NAME);
            if (alias!=null && !User.isAlias(alias)) {
               getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
               return new StringRepresentation("The alias '"+alias+"' does not contain all letters or digits.");
            }
            if ((alias!=null && !alias.equals(user.getAlias())) ||
                (alias==null && !user.getAlias().equals(user.getUser().getAlias())) ){
               // rename or unset
               try {
                  if (alias!=null && alias.equals(user.getUser().getAlias())) {
                     // unset
                     if (!user.changeAlias(null)) {
                        getResponse().setStatus(Status.CLIENT_ERROR_CONFLICT);
                        return new StringRepresentation("The alias '"+alias+"' is not available.");
                     }
                  } else {
                     if (!user.changeAlias(alias)) {
                        getResponse().setStatus(Status.CLIENT_ERROR_CONFLICT);
                        return new StringRepresentation("The alias '"+alias+"' is not available.");
                     }
                  }
               } catch (SQLException ex) {
                  getContext().getLogger().log(Level.SEVERE,"Database error during while changing alias: "+ex.getMessage(),ex);
                  getResponse().setStatus(Status.CLIENT_ERROR_CONFLICT);
                  return new StringRepresentation("The alias '"+alias+"' is not available.");
               }
            }
            if (name!=null) {
               String value = name.getText();
               getContext().getLogger().info("Setting name to: "+value);
               if (!value.equals(user.getName())) {
                  // set name
                  user.setName(value);
               }
            } else {
               if (user.getName()!=null) {
                  user.setName(null);
               }
            }
            if (email!=null) {
               String value = email.getText();
               if (!value.equals(user.getEmail())) {
                  // set email
                  user.setEmail(value);
               }
            } else {
               if (user.getEmail()!=null) {
                  user.setEmail(null);
               }
            }
            getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
            return null;
         } else {
            getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
            return new StringRepresentation("The user was not found.");
         }
      } catch (IllegalArgumentException ex) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("Bad UUID value specified: "+ex.getMessage());
      } catch (SQLException ex) {
         getContext().getLogger().log(Level.SEVERE,"Database error during user modify: "+ex.getMessage(),ex);
         getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
         return new StringRepresentation("Exception during processing, see logs.");
      }
   }
   
   public Representation post(Representation entity)
   {
      if (!XMLRepresentationParser.isXML(entity.getMediaType())) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("Non-XML media type for entity body: "+entity.getMediaType().getName());
      }
      Document doc = null;
      
      try {
         DocumentDestination dest = new DocumentDestination();
         postParser.parse(entity,dest);
         doc = dest.getDocument();
      } catch (Exception ex) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("XML parse error: "+ex.getMessage());
      }
      
      try {
         RealmUser user = fetch();
         if (user!=null) {
            Element top = doc.getDocumentElement();
            if (top.getName().equals(XML.GROUP_NAME)) {
               if (facet==null) {
                  getResponse().setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
                  return null;
               }
               if (!facet.equals(GROUP_FACET)) {
                  getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                  return null;
               }
               if (facetId!=null || facetName!=null) {
                  getResponse().setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
                  return null;
               }
               String sid = top.getAttributeValue("id");
               String name = top.getAttributeValue("alias");
               Group group = null;
               if (sid!=null) {
                  group = db.getGroup(user.getRealm(),UUID.fromString(sid));
               }
               if (name!=null && group==null) {
                  group = db.getGroup(user.getRealm(),name);
               }
               if (group==null) {
                  getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
                  return new StringRepresentation("Cannot find group "+name);
               } else {
                  user.addGroup(group);
                  getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
                  return null;
               }
            } else if (top.getName().equals(XML.PASSWORD_NAME)) {
               String password = top.getText();
               try {
                  user.getUser().setPassword(password);
                  getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
                  return null;
               } catch (NoSuchAlgorithmException ex) {
                  getContext().getLogger().log(Level.SEVERE,"Error while setting password: "+ex.getMessage(),ex);
                  getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
                  return new StringRepresentation("Algorithm encoding error while setting password.");
               }
            } else {
               getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
               return new StringRepresentation("Element not understood: "+top.getName());
            }

         } else {
            getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
            return new StringRepresentation("The user was not found.");
         }
      } catch (IllegalArgumentException ex) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("Bad UUID value specified: "+ex.getMessage());
      } catch (SQLException ex) {
         getContext().getLogger().log(Level.SEVERE,"Database error during user delete: "+ex.getMessage(),ex);
         getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
         return new StringRepresentation("Exception during processing, see logs.");
      }
   }
   
   protected RealmUser fetch()
      throws SQLException
   {
      Realm realm = (Realm)getRequest().getAttributes().get(AuthApplication.REALM_ATTR);
      /*
      Realm realm = null;
      if (name!=null) {
         realm = db.getRealm(name);
      }
      if (suuid!=null) {
         UUID id = UUID.fromString(suuid);
         realm = db.getRealm(id);
      }
       */
      if (realm!=null) {
         RealmUser user = null;
         if (userAlias!=null) {
            user = db.getRealmUser(realm,userAlias);
         }
         if (userId!=null) {
            UUID id = UUID.fromString(userId);
            user = db.getRealmUser(realm,id);
         }
         return user;
      }
      return null;
   }
   
   protected Group fetchGroup(RealmUser user)
      throws SQLException,IllegalArgumentException
   {
      Group group = null;
      if (facetName!=null) {
         group = db.getGroup(user.getRealm(),facetName);
      }
      if (facetId!=null) {
         UUID id = UUID.fromString(facetId);
         group = db.getGroup(user.getRealm(),id);
      }
      return group;
   }
   
   public Representation delete() {
      try {
         RealmUser user = fetch();
         if (user!=null) {
            if (facet!=null) {
               if (facet.equals(GROUP_FACET)) {
                  if (facetName==null && facetId==null) {
                     getResponse().setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
                     return null;
                  } else {
                     Group group = fetchGroup(user);
                     if (group!=null) {
                        if (user.removeGroup(group)) {
                           getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
                           return null;
                        } else {
                           getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                           return null;
                        }
                     } else {
                        getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                        return null;
                     }
                  }
               } else {
                  getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                  return null;
               }
            } else {
               user.delete();
               getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
               return null;
            }
         } else {
            getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
            return new StringRepresentation("Realm user was not found.");
         }
      } catch (IllegalArgumentException ex) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("Bad UUID value specified: "+ex.getMessage());
      } catch (SQLException ex) {
         getContext().getLogger().log(Level.SEVERE,"Database error during user delete: "+ex.getMessage(),ex);
         getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
         return new StringRepresentation("Exception during processing, see logs.");
      }
   }
  
}
